<template>
  <div class="ele-body ele-body-layout">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>搜索计划报告</span>
      </div>
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        class="ele-form-search"
        label-width="75px"
        @keyup.enter.native="reload"
        @submit.native.prevent
      >
        <div class="app-container">
          <div class="filter-container">
            <el-select
              v-model="where.bazaarId"
              clearable
              placeholder="推广市场"
              style="width: 180px; margin-right: 6px"
              @change="changebazaarId"
            >
              <template v-for="item in bazaarList">
                <el-option
                  v-if="item.status === 1"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </template>
            </el-select>

            <el-select
              v-model="where.customerid"
              class="filter-item"
              clearable
              placeholder="归属客户"
              style="width: 140px"
              @change="reload"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

            <el-select
              v-model="where.contact"
              class="filter-item"
              clearable
              placeholder="负责人"
              style="width: 140px"
              @change="reload"
            >
              <el-option
                v-for="item in principalList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

            <el-select
              v-model="where.userId"
              clearable
              placeholder="推广账户"
              style="width: 180px; margin-right: 6px"
              @change="reload"
            >
              <template v-for="item in expandList">
                <el-option
                  v-if="item.status === 1"
                  :key="item.userid"
                  :label="item.username"
                  :value="item.userid"
                />
              </template>
            </el-select>

            <el-select
              v-model="where.status"
              clearable
              placeholder="计划状态"
              style="width: 180px; margin-right: 6px"
              @change="reload"
            >
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

            <el-input
              v-model="where.campaignName"
              class="filter-item"
              clearable
              placeholder="计划名称"
              style="width: 180px"
              @clear="reload"
            />

            <el-date-picker
              v-model="daterange"
              :clearable="false"
              :picker-options="pickerOptions"
              end-placeholder="数据结束日期"
              range-separator="-"
              start-placeholder="数据开始日期"
              style="width: 226px; margin-right: 6px"
              type="datetimerange"
              unlink-panels
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="onDateRangeChoose"
            />

            <el-button
              icon="el-icon-search"
              style="margin-right: 6px"
              type="primary"
              @click="reload"
              >搜索
            </el-button>

            <el-button
              icon="el-icon-refresh"
              style="margin-left: 2px"
              @click="reset"
              >重置
            </el-button>
          </div>
        </div>
      </el-form>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :highlight-current-row="true"
        :max-height="defaultHeight"
        :parse-data="parseData"
        :selection.sync="selection"
        :summary-method="summaries"
        :where="where"
        show-summary
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            v-if="$hasPermission('semplan:budget')"
            :disabled="selection.length === 0"
            plain
            icon="el-icon-money"
            size="small"
            @click="SetBudgetBatch"
            >设置推广预算
          </el-button>

          <el-button
            v-if="$hasPermission('semplan:userStat')"
            :disabled="selection.length === 0"
            plain
            icon="el-icon-set-up"
            size="small"
            @click="SetPauseBatch"
            >设置启用/暂停
          </el-button>

          <el-button
            v-if="$hasPermission('semplan:schedule')"
            :disabled="selection.length === 0"
            plain
            icon="el-icon-time"
            size="small"
            @click="SetHourBatch"
            >设置推广时段
          </el-button>

          <el-button
            v-if="$hasPermission('semplan:regionTarget')"
            :disabled="selection.length === 0"
            plain
            icon="el-icon-_shop"
            size="small"
            @click="setRegionTargetBatch"
            >设置推广地域
          </el-button>

          <el-button
            v-if="$hasPermission('semplan:words')"
            :disabled="selection.length === 0"
            plain
            icon="el-icon-_shop"
            size="small"
            @click="SetWordBatch"
            >否定关键词
          </el-button>

          <el-button
            v-if="$hasPermission('semplan:cloud')"
            plain
            icon="el-icon-refresh-right"
            size="small"
            @click="SetCloudBatch"
            >获取最新数据
          </el-button>
        </template>

        <!-- 推广账户列 -->
        <template slot="userId" slot-scope="{ row }">
          <template v-for="item in tempexpandList">
            <span v-if="row.userId === item.userid" :key="item.id">
              {{ item.username }}
            </span>
          </template>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaarId" slot-scope="{ row }">
          <template v-for="item in bazaarList">
            <span v-if="row.bazaarId === item.id" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- 推广计划状态 -->
        <template slot="status" slot-scope="{ row }">
          <el-tag v-if="row.status === 21" size="mini" type="success"
            >有效
          </el-tag>
          <el-tag v-if="row.status === 22" size="mini" type="info"
            >处于暂停时段
          </el-tag>
          <el-tag v-if="row.status === 23" size="mini" type="info"
            >暂停推广
          </el-tag>
          <el-tag v-if="row.status === 24" size="mini">推广计划预算不足</el-tag>
          <el-tag v-if="row.status === 25" size="mini" type="info"
            >账户预算不足
          </el-tag>
        </template>

        <!-- 每日预算列 -->
        <template slot="budget" slot-scope="{ row }">
          <el-link :underline="false" @click="openBudgetBatch(row)"
            >{{ row.budget ? row.budget : "不限定预算" }}
            <i class="el-icon-edit-outline"></i
          ></el-link>
        </template>

        <!-- 推广地域列 -->
        <template slot="regionTarget" slot-scope="{ row }">
          <el-link
            v-if="!row.regionName"
            :underline="false"
            @click="openRegionTarget(row)"
          >
            未设置 <i class="el-icon-edit-outline"></i>
          </el-link>
          <el-link
            v-if="row.regionName"
            :underline="false"
            @click="openRegionTarget(row)"
          >
            {{ row.regionName }} <i class="el-icon-edit-outline"></i>
          </el-link>
        </template>

        <!-- 推广地域列 -->
        <template slot="schedule" slot-scope="{ row }">
          <el-link
            v-if="row.schedule.length === 0"
            :underline="false"
            @click="openScheduleEdit(row)"
          >
            全部时段 <i class="el-icon-edit-outline"></i>
          </el-link>
          <el-link
            v-if="row.schedule.length > 0"
            :underline="false"
            @click="openScheduleEdit(row)"
          >
            自定义时段 <i class="el-icon-edit-outline"></i>
          </el-link>
        </template>

        <!-- 否则关键词列 -->
        <template slot="negativeWords" slot-scope="{ row }">
          <el-link
            v-if="
              row.negativeWords.length === 0 &&
              row.exactNegativeWords.length === 0
            "
            :underline="false"
            @click="openNegativeWordsEdit(row)"
          >
            未设置 <i class="el-icon-edit-outline"></i>
          </el-link>
          <el-link
            v-if="
              row.negativeWords.length > 0 || row.exactNegativeWords.length > 0
            "
            :underline="false"
            @click="openNegativeWordsEdit(row)"
          >
            已设置 <i class="el-icon-edit-outline"></i>
          </el-link>
        </template>

        <!-- 同步时间列 -->
        <template slot="cloudDatatime" slot-scope="{ row }">
          {{ formatTime(row.datatime) }}
        </template>

        <!-- 点击率列 -->
        <template slot="ctr" slot-scope="{ row }">
          <span>{{ row.ctr }}% </span>
        </template>

        <!-- 现金消费列 -->
        <template slot="cash" slot-scope="{ row }">
          <el-popover
            placement="top-start"
            popper-class="cash-remove-popover"
            title="消费明细"
            trigger="hover"
            width="200"
            @hide="popoverHide"
          >
            现金消费{{ row.cash }}元, 账户返点: {{ row.rebate }}
            <span slot="reference" style="cursor: pointer">{{ row.cash }}</span>
          </el-popover>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 预算编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="
        BudgetForm.id
          ? '为[' + BudgetForm.campaignName + ']设置计划每日预算'
          : '设置计划每日预算'
      "
      :visible.sync="BudgetShowEdit"
      custom-class="ele-dialog-form"
      width="460px"
      @closed="BudgetForm = {}"
    >
      <el-form
        ref="BudgetForm"
        :model="BudgetForm"
        :rules="BudgetRules"
        label-width="82px"
      >
        <el-form-item label="预算类型:">
          <el-radio v-model="BudgetForm.budgetType" :label="0"
            >不设置预算
          </el-radio>
          <el-radio v-model="BudgetForm.budgetType" :label="1"
            >自定义每日预算
          </el-radio>
        </el-form-item>
        <el-form-item
          v-if="this.BudgetForm.budgetType"
          label="账户预算:"
          prop="budget"
        >
          <el-input-number
            v-model="BudgetForm.budget"
            :controls="false"
            :max="10000000"
            :min="50"
            class="ele-fluid ele-text-left"
            controls-position="right"
            placeholder="取值范围：[50, Min(10000000, 账户预算)]"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="BudgetShowEdit = false">关闭</el-button>
        <el-button
          :loading="BudgetLoading"
          type="primary"
          @click="setBudgetSave"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 状态编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="'设置计划状态'"
      :visible.sync="PauseShowEdit"
      custom-class="ele-dialog-form"
      width="420px"
      @closed="PauseForm = {}"
    >
      <el-form ref="PauseForm" :model="PauseForm" label-width="82px">
        <el-form-item label="暂停状态:">
          <el-radio v-model="PauseForm.pause" :label="0">启用</el-radio>
          <el-radio v-model="PauseForm.pause" :label="1">暂停</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="PauseShowEdit = false">关闭</el-button>
        <el-button :loading="PauseLoading" type="primary" @click="setPauseSave"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 时段编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="
        HourForm.id
          ? '为[' + HourForm.campaignName + ']计划修改时段'
          : '设置计划推广时段'
      "
      :visible.sync="HourShowEdit"
      class="hour-time-dialog"
      custom-class="ele-dialog-form"
      width="636px"
      @closed="HourForm = {}"
    >
      <el-form ref="HourForm" :model="HourForm" label-width="82px">
        <el-form-item label="推广时段:">
          <template>
            <el-radio v-model="HourForm.hourType" :label="0">全天时段</el-radio>
            <el-radio v-model="HourForm.hourType" :label="1"
              >自定义计划时段
            </el-radio>
          </template>
        </el-form-item>
        <div v-if="HourForm.hourType" class="vTimeMachine">
          <div class="vTimeBox">
            <div class="vTwrap">
              <div class="TimetopSquareBox clearFix">
                <ul class="leftSquareY clearFix">
                  <li></li>
                  <li>周一</li>
                  <li>周二</li>
                  <li>周三</li>
                  <li>周四</li>
                  <li>周五</li>
                  <li>周六</li>
                  <li>周日</li>
                </ul>
                <div class="TimerightWrap">
                  <ul class="TimetopSquareX clearFix" style="width: 502px">
                    <li>00:00</li>
                    <li>02:00</li>
                    <li>04:00</li>
                    <li>06:00</li>
                    <li>08:00</li>
                    <li>10:00</li>
                    <li>12:00</li>
                    <li>14:00</li>
                    <li>16:00</li>
                    <li>18:00</li>
                    <li>20:00</li>
                    <li>22:00</li>
                    <li>24:00</li>
                  </ul>

                  <div
                    @mousedown="handleMousedown"
                    @mouseleave="handleMouseleave"
                    @mousemove="handleMousemove"
                    @mouseup="handleMouseup"
                  >
                    <ul class="TimeSquareX clearFix" style="width: 482px">
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 1)"
                            :data-x="item"
                            data-y="0"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 2)"
                            :data-x="item"
                            data-y="1"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 3)"
                            :data-x="item"
                            data-y="2"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 4)"
                            :data-x="item"
                            data-y="3"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 5)"
                            :data-x="item"
                            data-y="4"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 6)"
                            :data-x="item"
                            data-y="5"
                          ></li>
                        </ul>
                      </li>
                      <li class="row">
                        <ul class="rowList clearFix">
                          <li
                            v-for="(item, i) in HourList"
                            :key="i"
                            :class="isHourSelected(item, 7)"
                            :data-x="item"
                            data-y="6"
                          ></li>
                        </ul>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
              <div
                class="TimebottomBox clearFix"
                style="width: 520px"
                @click="HourDayClick"
              >
                <span class="totalText">时段</span>
                <ul class="totalSquareX clearFix">
                  <li
                    v-for="(item, i) in HourList"
                    :key="i"
                    :data-x="item"
                    style="width: 20px"
                  ></li>
                </ul>
              </div>
            </div>
            <div class="TimesignBox">
              <span class="bgColor"></span>
              <span>广告投放时段</span>
              <span
                class="bgColor"
                style="background-color: #fff; border: 1px solid #eee"
              ></span>
              <span>未投放时段</span>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="HourShowEdit = false">关闭</el-button>
        <el-button :loading="HourLoading" type="primary" @click="HourSave"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 否定关键词编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="
        WordForm.id
          ? '为[' + WordForm.campaignName + ']计划否定关键词'
          : '设置计划否定关键词'
      "
      :visible.sync="WordShowEdit"
      custom-class="ele-dialog-form"
      width="640px"
      @closed="WordForm = {}"
    >
      <el-form ref="WordForm" :model="WordForm" label-width="0px">
        <el-form-item style="margin-bottom: 0px; margin-left: 0px">
          <template>
            <span class="el-checkbox__label" style="margin-left: -10px"
              >短语否定关键词</span
            >
            <el-popover
              content="当且仅当网民的搜索词中完全包含短语否定关键词时，您的推广结果将不会展现。"
              placement="bottom-start"
              trigger="hover"
              width="200"
            >
              <i
                slot="reference"
                class="el-tooltip el-icon-_question"
                style="
                  cursor: pointer;
                  vertical-align: middle;
                  margin-left: 8px;
                  margin-top: -3px;
                "
              ></i>
            </el-popover>
            <el-input
              v-model="WordForm.negativeWords"
              :rows="8"
              placeholder="请输入短语否定关键词"
              resize="none"
              style="box-shadow: var(--header-light-shadow)"
              type="textarea"
              @input="negativeWordsChange"
            >
            </el-input>
            <span
              class="el-input__count"
              style="
                color: var(--color-info);
                position: absolute;
                right: 20px;
                top: 180px;
                font-size: 12px;
              "
            >
              {{ WordnegativeWordsCurLen }}/{{ WordnegativeWordsMaxLen }}</span
            >
            <span
              v-if="
                this.WordnegativeWordsMaxLen - this.WordnegativeWordsCurLen < 0
              "
              class="el-checkbox__label"
              style="margin-left: -10px; color: red; font-size: 12px"
              >短语否定关键词已超出{{
                Math.abs(
                  this.WordnegativeWordsMaxLen - this.WordnegativeWordsCurLen
                )
              }}个
            </span>
          </template>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px; margin-left: 0px">
          <template>
            <span class="el-checkbox__label" style="margin-left: -10px"
              >精确否定关键词</span
            >
            <el-popover
              content="当且仅当网民的搜索词与精确否定关键词完全一致时，您的推广结果将不会展现。"
              placement="bottom-start"
              trigger="hover"
              width="200"
            >
              <i
                slot="reference"
                class="el-tooltip el-icon-_question"
                style="
                  cursor: pointer;
                  vertical-align: middle;
                  margin-left: 8px;
                  margin-top: -3px;
                "
              ></i>
            </el-popover>
            <el-input
              v-model="WordForm.exactNegativeWords"
              :rows="8"
              placeholder="请输入精确否定关键词"
              resize="none"
              style="box-shadow: var(--header-light-shadow)"
              type="textarea"
              @input="exactNegativeWordsChange"
            >
            </el-input>
            <span
              class="el-input__count"
              style="
                color: var(--color-info);
                position: absolute;
                right: 20px;
                top: 180px;
                font-size: 12px;
              "
            >
              {{ WordexactNegativeWordsCurLen }}/{{
                WordexactNegativeWordsMaxLen
              }}</span
            >
            <div v-if="WordRepeatedKeyword.length > 0">
              <span
                class="el-checkbox__label"
                style="margin-left: -10px; color: red; font-size: 12px"
                >精确否定关键词与短语否定关键词存在重复，无法确定，请及时调整，共{{
                  WordRepeatedKeyword.length
                }}个
              </span>
              <div style="position: absolute; bottom: 0px; right: 0px">
                <el-link
                  :underline="false"
                  type="primary"
                  @click="WordNegativeWordsView"
                  >查看
                </el-link>
                <el-link
                  :underline="false"
                  type="primary"
                  @click="WordNegativeWordsDelete"
                  >删除
                </el-link>
              </div>
            </div>
            <span
              v-if="
                this.WordexactNegativeWordsMaxLen -
                  this.WordexactNegativeWordsCurLen <
                0
              "
              class="el-checkbox__label"
              style="margin-left: -10px; color: red; font-size: 12px"
              >精确否定关键词已超出{{
                Math.abs(
                  this.WordexactNegativeWordsMaxLen -
                    this.WordexactNegativeWordsCurLen
                )
              }}个
            </span>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="WordShowEdit = false">关闭</el-button>
        <el-button :loading="WordLoading" type="primary" @click="setWordSave"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹出同步窗口 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="'获取最新数据'"
      :visible.sync="synchronousShow"
      class="ele-dialog-view"
      custom-class="ele-dialog-form"
      width="640px"
      @closed="synchronousForm = {}"
    >
      <el-form ref="synchronousForm" :model="synchronousForm">
        <div style="height: 350px">
          <div
            :style="{
              'border-radius': '4px',
              float: 'left',
              'margin-left': '10px',
              width: '170px',
              'pointer-events': isLeftDisabled ? 'none' : '',
              opacity: isLeftDisabled ? '.7' : '1.0',
            }"
          >
            <div style="margin: 6px 0"><span>请选择要同步的账户</span></div>
            <el-checkbox
              v-model="handleCheckAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选/反选
            </el-checkbox>
            <div style="margin: 10px 0"></div>
            <div class="ele-left-layout">
              <el-checkbox-group
                v-model="checkedUserId"
                @change="handlecheckedUserIdChange"
              >
                <template v-for="item in tempexpandList">
                  <el-checkbox
                    v-if="item.status === 1"
                    :key="item.id"
                    :label="item.userid"
                    style="width: 140px; font-size: 12px"
                    >{{ item.username }}
                  </el-checkbox>
                </template>
              </el-checkbox-group>
            </div>
          </div>
          <div class="ele-right-layout">
            <div style="margin: 6px 0"><span>同步结果</span></div>
            <div>
              <el-input
                v-model="synchronousResult"
                :readonly="true"
                resize="none"
                type="textarea"
              />
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button size="medium" @click="synchronousShow = false"
          >取消
        </el-button>
        <el-button
          :loading="synchronousLoading"
          size="medium"
          type="primary"
          @click="synchronousSave"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 设置推广地域弹窗 -->
    <vue-planregional
      :data="current"
      :visible.sync="showRegionTarget"
      @done="reload"
    />

    <div
      v-if="HourLayerTips"
      ref="fyLayerTips"
      class="TimeLayer"
      style="display: none"
    ></div>

    <div id="border" class="ele-border"></div>
  </div>
</template>

<script>
import VuePlanregional from "./vue-planregional";

export default {
  name: "semCampaign",
  components: { VuePlanregional },
  data() {
    return {
      //数据合计
      total: Object,

      //归属客户
      customerList: [],
      //负责人
      principalList: [],

      // 计划状态
      statusList: [
        { id: 21, name: "有效" },
        { id: 22, name: "处于暂停时段" },
        { id: 23, name: "暂停推广" },
        { id: 24, name: "计划预算不足" },
        { id: 25, name: "账户预算不足" },
      ],

      // 预算弹窗
      BudgetShowEdit: false,
      // 预算表单
      BudgetForm: {},
      // 预算加载中
      BudgetLoading: false,
      // 预算表单验证规则
      BudgetRules: {
        budget: [
          {
            required: true,
            type: "string",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.BudgetForm.budgetType === 1 && !value) {
                return callback(new Error("请输入账户预算"));
              }
              callback();
            },
          },
        ],
      },

      // 当前数据
      current: null,

      // 是否显示地域弹窗
      showRegionTarget: false,

      // 状态弹窗
      PauseShowEdit: false,
      // 状态表单
      PauseForm: {},
      // 状态加载中
      PauseLoading: false,

      // 否定关键词弹窗
      WordShowEdit: false,
      // 否定关键词表单
      WordForm: {},
      // 否定关键词加载中
      WordLoading: false,
      // 最大输入精准文字长度, 根据用户等级（账户对象userLevel字段）上限不等：未生效客户(4)：200；一星客户(3)：400；二星客户(2)：700；三星客户(1)：900；
      WordexactNegativeWordsMaxLen: 200,
      //大输入短语文字长度, 根据用户等级（账户对象userLevel字段）上限不等：未生效客户(4)：200；一星客户(3)：400；二星客户(2)：700；三星客户(1)：900；
      WordnegativeWordsMaxLen: 200,
      // 当前输入精准文字长度
      WordexactNegativeWordsCurLen: 0,
      // 当前输入短语文字长度
      WordnegativeWordsCurLen: 0,
      // 输入关键词是否重复
      WordRepeatedKeyword: [],

      // 时段弹窗
      HourShowEdit: false,
      // 时段TIPS
      HourLayerTips: false,
      // 时段表单
      HourForm: {},
      // 时段加载中
      HourLoading: false,
      // 时段开始拖动
      HourStartSelect: {},
      // 时段结束拖动
      HourEndSelect: {},
      // 时段开始拖动
      HourClassName: "",
      // 循环时段
      HourList: [
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
        20, 21, 22, 23,
      ],

      // 同步账户选中账户
      checkedUserId: [],
      // 同步账户选中账户
      handleCheckAll: false,
      // 同步账户选中账户
      isIndeterminate: false,
      // 同步账户选中账户
      isLeftDisabled: false,

      // 同步表单数据
      synchronousForm: {},
      // 同步表单按钮
      synchronousLoading: false,
      // 是否显示编辑弹窗
      synchronousShow: false,
      // 同步数据结果
      synchronousResult: "",

      // 账户列表
      tempexpandList: [],
      // 账户列表
      expandList: [],
      //市场列表
      bazaarList: [],
      // 表格高度
      defaultHeight: 0,
      // 筛选日期范围
      daterange: this.getDaterange(),
      // 日期时间选择器快捷项
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime());
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000);
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 7 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 15 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 30 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 90 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 180 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 365 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 表格数据接口
      url: "/SemPlan/read",
      // 表格列配置
      columns: [
        {
          columnKey: "selection",
          type: "selection",
          width: 45,
          align: "center",
        },
        {
          prop: "userId",
          label: "推广账户",
          slot: "userId",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "bazaarId",
          label: "推广市场",
          slot: "bazaarId",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "campaignName",
          label: "计划名称",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          width: 110,
          prop: "status",
          label: "计划状态",
          slot: "status",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          width: 100,
          prop: "budget",
          slot: "budget",
          label: "每日预算",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          width: 110,
          label: "推广地域",
          prop: "regionTarget",
          sortable: "custom",
          slot: "regionTarget",
          showOverflowTooltip: true,
        },
        {
          width: 100,
          label: "推广时段",
          prop: "schedule",
          sortable: "custom",
          slot: "schedule",
          showOverflowTooltip: true,
        },
        {
          width: 80,
          label: "否定词",
          prop: "negativeWords",
          sortable: "custom",
          slot: "negativeWords",
          showOverflowTooltip: true,
        },
        {
          prop: "impression",
          label: "展现",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "clicks",
          label: "点击",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cost",
          label: "消费",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cash",
          slot: "cash",
          label: "现金消费",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cpc",
          label: "CPC",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "ctr",
          slot: "ctr",
          label: "点击率",
          sortable: "custom",
          resizable: false,
        },
        {
          prop: "copynumber",
          label: "复制数",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "copycost",
          label: "复制成本",
          sortable: "custom",
          resizable: false,
        },
        {
          prop: "datatime",
          label: "同步时间",
          sortable: "custom",
          resizable: false,
          slot: "cloudDatatime",
          showOverflowTooltip: true,
        },
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 鼠标移动区域
      downX: 0,
      downY: 0,
    };
  },

  watch: {
    HourShowEdit: function (obj) {
      this.HourLayerTips = obj;
    },
  },

  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },

  methods: {
    summaries(param) {
      const { columns, data } = param,
        createDiv = function (t1, t2) {
          return (() => {
            return (
              <el-col>
                <el-col class="el-table_target_sum">{t1}</el-col>
                <el-col class="el-table_target_bar"></el-col>
                <el-col class="el-table_target_total">{t2}</el-col>
              </el-col>
            );
          })();
        };
      let result = [],
        sum1 = 0,
        sum2 = 0,
        sum3 = 0,
        sum4 = 0,
        sum5 = 0,
        sum6 = 0,
        sum7 = 0,
        sum8 = 0,
        sum9 = 0;
      columns.forEach((column, index) => {
        switch (column.property) {
          case "negativeWords":
            result[index] = createDiv("小计", "合计");
            break;

          case "impression":
            sum1 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum1, this.total.impression);
            break;

          case "clicks":
            sum2 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum2, this.total.clicks);
            break;

          case "cost":
            sum3 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum3, this.total.cost);
            break;

          case "cash":
            sum4 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum4, this.total.cash);
            break;

          case "cpc":
            sum5 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum5, this.total.cpc);
            break;

          case "ctr":
            sum6 = (sum2 / sum1) * 100;
            if (isNaN(sum6)) {
              sum6 = 0;
            }
            sum9 = (this.total.clicks / this.total.impression) * 100;
            if (isNaN(sum9)) {
              sum9 = 0;
            }
            result[index] = createDiv(
              sum6.toFixed(2) + "%",
              sum9.toFixed(2) + "%"
            );
            break;

          case "copynumber":
            sum7 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum7, this.total.copynumber);
            break;

          case "copycost":
            sum8 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum8, this.total.copycost);
            break;
        }
      });
      return result;
    },

    getcolumn(data, column, integer) {
      if (data.length === 0) {
        return 0;
      }
      let sums = 0;
      const values = data.map((item) => Number(item[column]));
      if (!values.every((value) => isNaN(value))) {
        sums = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      }
      if (integer) {
        return sums;
      }
      return sums.toFixed(2);
    },

    popoverHide() {
      const popover = document.getElementsByClassName("cash-remove-popover");
      for (let i = 0; i < popover.length; i++) {
        popover[i].remove();
      }
    },

    parseData(res) {
      if (res.code === 0) {
        this.tempexpandList = res.expand;
        this.customerList = res.customer;
        this.principalList = res.principal;
        this.bazaarList = res.bazaar;
        this.total = res.total;
      }
      return {
        code: res.code,
        data: res.data,
        count: res.count,
        msg: res.msg,
      };
    },

    handleCheckAllChange(val) {
      let userId = [];
      for (let i = 0; i < this.tempexpandList.length; i++) {
        if (this.tempexpandList[i].status === 1) {
          userId.push(this.tempexpandList[i].userid);
        }
      }
      this.checkedUserId = val ? userId : [];
      this.isIndeterminate = false;
      this.synchronousResult = "";
    },

    handlecheckedUserIdChange(value) {
      let checkedCount = 0;
      for (let i = 0; i < this.tempexpandList.length; i++) {
        if (this.tempexpandList[i].status === 1) {
          checkedCount++;
        }
      }
      let count = value.length;
      this.synchronousResult = "";
      this.handleCheckAll = count === checkedCount;
      this.isIndeterminate = count > 0 && count < checkedCount;
    },

    handleMouseup(t) {
      const border = document.getElementById("border");
      border.style.display = "none";
      this.HourEndSelect = {
        x: parseInt(t.target.dataset.x || t.target.dataset.clientX, 0),
        y: parseInt(t.target.dataset.y || t.target.dataset.clientY, 0),
      };
      this.setHandleState();
      t.preventDefault();
      t.stopPropagation();
    },

    handleMouseleave(t) {
      let border = document.getElementById("border");
      border.style.display = "none";
      if (!this.$refs.fyLayerTips) return !1;
      this.$refs.fyLayerTips.setAttribute("style", "display:none; top:-9999px");
      this.setHandleState();
      t.preventDefault();
      t.stopPropagation();
    },

    handleMousedown(t) {
      this.downX = t.clientX;
      this.downY = t.clientY;
      let border = document.getElementById("border");
      border.style.top = this.downY + "px";
      border.style.left = this.downX + "px";
      border.style.display = "block";

      this.HourEndSelect = {};
      this.HourStartSelect = {};
      if ("li" !== t.target.nodeName.toLowerCase()) return !1;
      this.HourStartSelect = {
        x: parseInt(t.target.dataset.x || t.target.dataset.clientX, 0),
        y: parseInt(t.target.dataset.y || t.target.dataset.clientY, 0),
      };
      "select" === t.target.className
        ? (t.target.className = "")
        : (t.target.className = "select");
      this.HourClassName = t.target.className;

      t.preventDefault();
      t.stopPropagation();
    },

    handleMousemove(e) {
      const border = document.getElementById("border");
      if (e.clientX > this.downX) {
        border.style.left = this.downX + "px";
      } else {
        border.style.left = e.clientX + "px";
      }
      if (e.clientY > this.downY) {
        border.style.top = this.downY - 62 + "px";
      } else {
        border.style.top = e.clientY - 62 + "px";
      }
      border.style.width = Math.abs(e.clientX - this.downX) + "px";
      border.style.height = Math.abs(e.clientY - this.downY) + "px";

      if ("li" !== e.target.nodeName.toLowerCase()) return !1;
      if (!this.$refs.fyLayerTips) return !1;
      let _x = parseInt(e.target.dataset.x || e.target.dataset.clientX, 0);
      let _y = parseInt(e.target.dataset.y || e.target.dataset.clientY, 0);
      const getTimeFrame = function (e) {
        if (e < 10) {
          return e + ":00 - 0" + (e + 1) + ":00";
        }
        return e + ":00 - " + (e + 1) + ":00";
      };
      const getWeekFrame = function (e) {
        return 0 === e
          ? "星期一"
          : 1 === e
          ? "星期二"
          : 2 === e
          ? "星期三"
          : 3 === e
          ? "星期四"
          : 4 === e
          ? "星期五"
          : 5 === e
          ? "星期六"
          : "星期天";
      };
      this.$refs.fyLayerTips.innerHTML =
        getWeekFrame(_y) +
        " " +
        getTimeFrame(_x) +
        " " +
        ("select" === e.target.className ? "投放" : "不投放");
      this.$refs.fyLayerTips.setAttribute(
        "style",
        "display:block; left:" + e.clientX + "px;top:" + (e.clientY - 30) + "px"
      );
      this.HourEndSelect = { x: _x, y: _y };

      e.preventDefault();
      e.stopPropagation();
    },

    HourDayClick(e) {
      if ("li" !== e.target.nodeName.toLowerCase()) return !1;
      "select" === e.target.className
        ? (e.target.className = "")
        : (e.target.className = "select");
      const elements = document.getElementsByTagName("li");
      for (let i = 0; i < elements.length; i++) {
        if (e.target.dataset.x === elements[i].dataset.x) {
          elements[i].className = e.target.className;
        }
      }
    },

    setHandleState() {
      if (!this.HourStartSelect || !this.HourEndSelect) {
        return false;
      }
      const elements = document.getElementsByTagName("li");
      for (let i = 0; i < elements.length; i++) {
        let x = elements[i].dataset.x,
          y = elements[i].dataset.y;
        let condition1 =
          this.HourStartSelect.y <= y &&
          this.HourEndSelect.y >= y &&
          this.HourStartSelect.x <= x &&
          this.HourEndSelect.x >= x;
        let condition2 =
          this.HourStartSelect.y >= y &&
          this.HourEndSelect.y <= y &&
          this.HourStartSelect.x <= x &&
          this.HourEndSelect.x >= x;
        let condition3 =
          this.HourStartSelect.y <= y &&
          this.HourEndSelect.y >= y &&
          this.HourStartSelect.x >= x &&
          this.HourEndSelect.x <= x;
        let condition4 =
          this.HourStartSelect.y >= y &&
          this.HourEndSelect.y <= y &&
          this.HourStartSelect.x >= x &&
          this.HourEndSelect.x <= x;
        if (condition1 || condition2 || condition3 || condition4) {
          elements[i].className = this.HourClassName;
        }
      }
      this.HourStartSelect = {};
      this.HourEndSelect = {};
    },

    setRegionTargetBatch() {
      if (!this.$hasPermission("semplan:regionTarget")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      const selectionArray = this.selection.map((d) => d.id);
      this.current = { ids: selectionArray };
      this.showRegionTarget = true;
    },

    SetHourBatch() {
      if (!this.$hasPermission("semplan:schedule")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.HourLoading = false;
      this.HourForm = { hourType: 0 };
      this.HourShowEdit = true;
    },

    SetPauseBatch() {
      if (!this.$hasPermission("semplan:userStat")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.PauseLoading = false;
      this.PauseForm = { pause: 0 };
      this.PauseShowEdit = true;
    },

    SetCloudBatch() {
      if (!this.$hasPermission("semplan:cloud")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.synchronousForm = {};
      this.synchronousResult = "";
      this.synchronousLoading = false;
      this.synchronousShow = true;
    },

    /* 开始同步账户 */
    synchronousSave() {
      if (this.checkedUserId.length === 0) {
        this.$message.error("请选择要同步的账户!");
        return;
      }
      this.$refs["synchronousForm"].validate((valid) => {
        if (valid) {
          this.isLeftDisabled = true;
          this.synchronousLoading = true;
          let requestArrayName = [],
            requestArray = [],
            userArrayName = [];
          for (let i = 0; i < this.tempexpandList.length; i++) {
            if (
              this.checkedUserId.indexOf(this.tempexpandList[i].userid) > -1
            ) {
              requestArrayName.push(
                "[" + this.tempexpandList[i].username + "] 开始同步数据.\n"
              );
              userArrayName.push(this.tempexpandList[i].username);
              requestArray.push(
                this.$http.put("/SemPlan/getCloud", {
                  userId: this.tempexpandList[i].userid,
                })
              );
            }
          }
          this.synchronousResult = requestArrayName.join("");
          Promise.all(requestArray)
            .then((items) => {
              items.forEach((item, index) => {
                requestArrayName.push(
                  "[" + userArrayName[index] + "] " + item.data.msg + "\n"
                );
              });
              this.synchronousResult = requestArrayName.join("");
              this.checkedUserId = [];
              this.isLeftDisabled = false;
              this.handleCheckAll = false;
              this.isIndeterminate = false;
              this.synchronousLoading = false;
              this.reload();
            })
            .catch((e) => {
              this.synchronousResult = "网络异常同步失败!";
              this.synchronousLoading = false;
              this.isLeftDisabled = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },

    /* 确定时段表单*/
    HourSave() {
      this.$refs["HourForm"].validate((valid) => {
        if (valid) {
          let schedule = [];
          this.HourLoading = true;
          const elements = document.getElementsByTagName("li");
          for (let i = 0; i < elements.length; i++) {
            if (elements[i].dataset.y && elements[i].className !== "select") {
              schedule.push({
                weekDay: parseInt(elements[i].dataset.y, 0) + 1,
                startHour: parseInt(elements[i].dataset.x, 0),
                endHour: parseInt(elements[i].dataset.x, 0) + 1,
              });
            }
          }
          this.HourForm.schedule = schedule;
          if (schedule.length === 168) {
            this.HourForm.schedule = [];
          }
          this.HourForm.selectId = this.selection.map((d) => d.id);
          this.$http
            .put("/SemPlan/setHour", this.HourForm)
            .then((res) => {
              this.HourLoading = false;
              if (res.data.code === 0) {
                this.HourShowEdit = false;
                let _message = res.data.data.join("<br/>");
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message: _message,
                  duration: 5000,
                  iconClass: "icon-ex",
                  type: _message.indexOf("code") === -1 ? "success" : "error",
                });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.HourLoading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },

    /*确定状态表单*/
    setPauseSave() {
      this.$refs["PauseForm"].validate((valid) => {
        if (valid) {
          this.PauseLoading = true;
          this.PauseForm.selectId = this.selection.map((d) => d.id);
          this.$http
            .put("/SemPlan/setPause", this.PauseForm)
            .then((res) => {
              this.PauseLoading = false;
              if (res.data.code === 0) {
                this.PauseShowEdit = false;
                this.$message({ type: "success", message: res.data.msg });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.PauseLoading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },

    // 打开批量设置否定关键词
    SetWordBatch() {
      if (!this.$hasPermission("semplan:words")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.WordLoading = false;
      this.WordShowEdit = true;
      this.WordnegativeWordsCurLen = 0;
      this.WordexactNegativeWordsCurLen = 0;
      this.WordForm = {};
    },

    // 打开单个设置否定关键词
    openNegativeWordsEdit(obj) {
      this.WordLoading = false;
      this.WordShowEdit = true;
      this.WordRepeatedKeyword = [];
      switch (obj.userLevel) {
        case 1:
          this.WordnegativeWordsMaxLen = 500;
          this.WordexactNegativeWordsMaxLen = 900;
          break;
        case 2:
          this.WordnegativeWordsMaxLen = 400;
          this.WordexactNegativeWordsMaxLen = 700;
          break;
        case 3:
          this.WordnegativeWordsMaxLen = 200;
          this.WordexactNegativeWordsMaxLen = 400;
          break;
        default:
          this.WordnegativeWordsMaxLen = 200;
          this.WordexactNegativeWordsMaxLen = 200;
      }

      let negativeWords = "";
      if (obj.negativeWords) {
        negativeWords = obj.negativeWords.join("\n");
        this.WordnegativeWordsCurLen = 0;
        for (let i = 0; i < obj.negativeWords.length; i++) {
          if (obj.negativeWords[i]) {
            this.WordnegativeWordsCurLen++;
          }
        }
      }

      let exactNegativeWords = "";
      if (obj.exactNegativeWords) {
        exactNegativeWords = obj.exactNegativeWords.join("\n");
        this.WordexactNegativeWordsCurLen = 0;
        for (let i = 0; i < obj.exactNegativeWords.length; i++) {
          if (obj.exactNegativeWords[i]) {
            this.WordexactNegativeWordsCurLen++;
          }
        }
      }

      this.WordForm = {
        id: obj.id,
        campaignName: obj.campaignName,
        negativeWords: negativeWords,
        exactNegativeWords: exactNegativeWords,
      };
    },

    // 短语关键词被改变
    negativeWordsChange(value) {
      if (value === "") {
        return false;
      }
      let exactNegativeWords = [];
      if (this.WordForm.exactNegativeWords) {
        exactNegativeWords = this.WordForm.exactNegativeWords.split("\n");
      }
      this.WordRepeatedKeyword = [];
      let negativeWords = value.split("\n");
      this.WordnegativeWordsCurLen = 0;
      for (let i = 0; i < negativeWords.length; i++) {
        if (negativeWords[i]) {
          this.WordnegativeWordsCurLen++;
          if (exactNegativeWords.length > 0) {
            if (
              exactNegativeWords.indexOf(negativeWords[i]) > -1 &&
              this.WordRepeatedKeyword.indexOf(negativeWords[i]) === -1
            ) {
              this.WordRepeatedKeyword.push(negativeWords[i]);
            }
          }
        }
      }
    },

    // 精准关键词被改变
    exactNegativeWordsChange(value) {
      if (value === "") {
        return false;
      }
      let negativeWords = [];
      if (this.WordForm.negativeWords) {
        negativeWords = this.WordForm.negativeWords.split("\n");
      }
      this.WordRepeatedKeyword = [];
      let exactNegativeWords = value.split("\n");
      this.WordexactNegativeWordsCurLen = 0;
      for (let i = 0; i < exactNegativeWords.length; i++) {
        if (exactNegativeWords[i]) {
          this.WordexactNegativeWordsCurLen++;
          if (negativeWords.length > 0) {
            if (
              negativeWords.indexOf(exactNegativeWords[i]) > -1 &&
              this.WordRepeatedKeyword.indexOf(exactNegativeWords[i]) === -1
            ) {
              this.WordRepeatedKeyword.push(exactNegativeWords[i]);
            }
          }
        }
      }
    },

    // 查看精准关键词
    WordNegativeWordsView() {
      this.$alert(
        this.WordRepeatedKeyword.join("<br>"),
        "精确否定关键词重复词",
        {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
          customClass: "el-message-plan",
        }
      );
    },

    // 删除精准关键词
    WordNegativeWordsDelete() {
      if (this.WordForm.exactNegativeWords) {
        let negativeWords = [];
        let exactNegativeWords = this.WordForm.exactNegativeWords.split("\n");
        for (let i = 0; i < exactNegativeWords.length; i++) {
          if (exactNegativeWords[i]) {
            if (
              this.WordRepeatedKeyword.indexOf(exactNegativeWords[i]) === -1 &&
              negativeWords.indexOf(exactNegativeWords[i]) === -1
            ) {
              negativeWords.push(exactNegativeWords[i]);
            }
          }
        }
        this.WordRepeatedKeyword = [];
        this.WordForm.exactNegativeWords = negativeWords.join("\n");
      }
    },

    // 确定关键词
    setWordSave() {
      if (this.WordRepeatedKeyword.length > 0) {
        return this.$message.error("精确否定关键词与短语否定关键词存在重复!");
      }
      // 验证短语长度
      if (this.WordForm.negativeWords) {
        let negativeWords = this.WordForm.negativeWords.split("\n");
        for (let i = 0; i < negativeWords.length; i++) {
          if (negativeWords[i].length > 40) {
            return this.$message.error("短语否定关键词单行不能超过40个!");
          }
        }
      }
      // 验证精准长度
      if (this.WordForm.exactNegativeWords) {
        let negativeWords = this.WordForm.exactNegativeWords.split("\n");
        for (let i = 0; i < negativeWords.length; i++) {
          if (negativeWords[i].length > 40) {
            return this.$message.error("精准否定关键词单行不能超过40个!");
          }
        }
      }
      this.$refs["WordForm"].validate((valid) => {
        if (valid) {
          this.WordLoading = true;
          this.WordForm.selectId = this.selection.map((d) => d.id);
          this.$http
            .put("/SemPlan/setWords", this.WordForm)
            .then((res) => {
              this.WordLoading = false;
              if (res.data.code === 0) {
                this.WordShowEdit = false;
                let _message = res.data.data.join("<br/>");
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message: _message,
                  duration: 5000,
                  iconClass: "icon-ex",
                  type: _message.indexOf("code") === -1 ? "success" : "error",
                });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.WordShowEdit = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },

    isHourSelected(x, y) {
      if (!this.HourForm.schedule) {
        return "";
      }
      for (let i = 0; i < this.HourForm.schedule.length; i++) {
        if (
          this.HourForm.schedule[i].weekDay === y &&
          this.HourForm.schedule[i].startHour === x
        ) {
          return "";
        }
      }
      return "select";
    },

    openScheduleEdit(row) {
      let hourType = 0;
      if (row.schedule.length > 0) {
        hourType = 1;
      }
      this.HourLoading = false;
      this.HourForm = {
        hourType: hourType,
        id: row.id,
        schedule: row.schedule,
        campaignId: row.campaignId,
        campaignName: row.campaignName,
      };
      this.HourShowEdit = true;
    },

    /*设置计划预算*/
    SetBudgetBatch() {
      if (!this.$hasPermission("semplan:budget")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.BudgetLoading = false;
      this.BudgetForm = { budgetType: 0 };
      this.BudgetShowEdit = true;
    },

    /*设置计划预算*/
    openBudgetBatch(row) {
      if (!this.$hasPermission("semplan:budget")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.BudgetLoading = false;
      this.BudgetForm = {
        id: row.id,
        budget: row.budget,
        budgetType: row.budget ? 1 : 0,
        campaignName: row.campaignName,
      };
      this.BudgetShowEdit = true;
    },

    /*确定预算表单*/
    setBudgetSave() {
      this.$refs["BudgetForm"].validate((valid) => {
        if (valid) {
          this.BudgetLoading = true;
          this.BudgetForm.selectId = this.selection.map((d) => d.id);
          this.$http
            .put("/SemPlan/setBudget", this.BudgetForm)
            .then((res) => {
              this.BudgetLoading = false;
              if (res.data.code === 0) {
                this.BudgetShowEdit = false;
                this.$message({ type: "success", message: res.data.msg });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.BudgetLoading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },

    /*设置账户推广地域*/
    openRegionTarget(row) {
      if (!this.$hasPermission("semplan:regionTarget")) {
        return this.$message.error("你没有权限执行此操作!");
      }
      this.$http
        .post("/SemPlan/regionTarget", { id: row.id })
        .then((res) => {
          if (res.data.code === 0) {
            let regionTarget = [];
            if (res.data.data.regionTarget) {
              regionTarget = res.data.data.regionTarget;
            }
            row.regionTarget = regionTarget;
            let checkedKeys = [];
            for (let i = 0; i < regionTarget.length; i++) {
              if (regionTarget[i].children.length === 0) {
                checkedKeys.push(regionTarget[i].id);
              }
              if (regionTarget[i].children.length > 0) {
                for (const item of regionTarget[i].children) {
                  checkedKeys.push(item.id);
                }
              }
            }
            row.defaultCheckedKeys = checkedKeys;
            this.current = row;
            this.showRegionTarget = true;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    changebazaarId(id) {
      let arrayList = [];
      this.where.userId = "";
      for (let i = 0; i < this.tempexpandList.length; i++) {
        if (this.tempexpandList[i].bazaarId === id) {
          arrayList.push(this.tempexpandList[i]);
        }
      }
      this.expandList = arrayList;
      this.reload();
    },

    /*默认时间*/
    getDaterange() {
      let start = new Date();
      start.setTime(start.getTime());
      start =
        start.getFullYear() +
        "-" +
        (start.getMonth() + 1) +
        "-" +
        start.getDate() +
        " 00:00:00";
      let end = new Date();
      end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
      end =
        end.getFullYear() +
        "-" +
        (end.getMonth() + 1) +
        "-" +
        end.getDate() +
        " 00:00:00";
      return [start, end];
    },

    /* 日期选择改变回调 */
    onDateRangeChoose() {
      if (this.daterange && this.daterange.length === 2) {
        this.where.createTimeStart = this.daterange[0];
        this.where.createTimeEnd = this.daterange[1];
      } else {
        this.where.createTimeStart = null;
        this.where.createTimeEnd = null;
      }
    },

    /*设置表格高度*/
    getHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      let daterange = this.getDaterange();
      if (daterange.length === 2) {
        this.where.createTimeStart = daterange[0];
        this.where.createTimeEnd = daterange[1];
      }
      this.daterange = daterange;
      this.reload();
    },

    /*时间格式化*/
    formatTime(value) {
      const stamp = new Date().getTime() - new Date(value).getTime();
      if (stamp >= 1000 * 60 * 60 * 24) {
        return ((stamp / 1000 / 60 / 60 / 24) | 0) + "天前";
      } else if (stamp >= 1000 * 60 * 60) {
        return ((stamp / 1000 / 60 / 60) | 0) + "小时前";
      } else if (stamp >= 60000) {
        //1分钟以内为：刚刚
        return ((stamp / 1000 / 60) | 0) + "分钟前";
      }
      return "刚刚";
    },
  },
};
</script>

<style scoped>
.ele-table-tool .is-disabled {
  cursor: not-allowed;
  filter: Alpha(opacity=0.35);
  -moz-opacity: 0.35;
  opacity: 0.35;
}

.hour-time-dialog /deep/ .el-dialog__body {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.vTimeBox {
  width: 540px;
  margin: 20px auto;
  margin-top: 10px;
  background-color: var(--table-header-background-color);
}

.vTimeBox * {
  margin: 0;
  padding: 0;
}

.vTimeBox ul,
li {
  list-style: none;
}

.clearFix:after {
  content: "";
  display: block;
  clear: both;
}

.TimesignBox {
  margin-top: 10px;
  padding-left: 45px;
}

.TimesignBox span {
  display: inline-block;
  vertical-align: middle;
  color: #333;
  font-size: 14px;
  margin-right: 10px;
}

.TimesignBox span.bgColor {
  width: 20px;
  height: 14px;
  background: #93c8fd;
}

.TimetopSquareBox .leftSquareY {
  float: left;
  margin-top: 10px;
  margin-left: 10px;
}

.TimetopSquareBox .leftSquareY li {
  height: 23px;
  line-height: 23px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
  font-size: 12px;
  border-bottom: 1px solid transparent;
}

.TimerightWrap {
  float: right;
  margin-right: -6px;
}

.TimetopSquareX li {
  float: left;
  line-height: 38px;
  text-align: center;
  width: 37px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #999;
  font-size: 12px;
}

.TimeSquareX {
  border: 1px solid #eee;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

.TimeSquareX .row + .row {
  border-top: 1px solid #eee;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

.TimeSquareX .rowList li {
  float: left;
  height: 22px;
  width: 20px;
  background: #fff;
  border-right: 1px solid #eee;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

.TimeSquareX .rowList li:last-child {
  border-right: none;
}

.TimebottomBox {
  margin-top: 5px;
}

.TimebottomBox .totalText {
  float: left;
  height: 24px;
  line-height: 24px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
  font-size: 12px;
  font-weight: bold;
  margin-left: 10px;
}

.TimebottomBox .totalSquareX {
  float: right;
  border: 1px solid #eee;
  margin-right: -6px;
}

.TimebottomBox .totalSquareX li {
  float: left;
  height: 22px;
  background: #fff;
  border-right: 1px solid #eee;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  cursor: pointer;
}

.TimebottomBox .totalSquareX li:last-child {
  border-right: none;
}

.TimebottomBox .totalSquareX li.select,
.TimeSquareX .rowList li.select {
  background: #93c8fd;
  border-right: none;
}

.vTimeMachine {
  margin-bottom: 15px;
  background-color: var(--table-header-background-color);
  border: 1px solid #e7e7e7;
}

.TimeLayer {
  position: absolute;
  z-index: 10000;
  border-radius: 2px;
  width: 200px;
  height: 30px;
  font-size: 12px;
  line-height: 30px;
  text-align: center;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  min-width: 150px;
  background-color: #fff;
  border-color: #d8d8d8;
}

.ele-left-layout {
  width: 186px;
  height: 262px;
  padding: 10px;
  margin-bottom: 10px;
  overflow-y: auto;
  border: 1px solid var(--border-color-base);
  box-shadow: var(--header-light-shadow);
}

.ele-right-layout {
  float: right;
  margin-top: 28px;
  width: 386px;
}

.ele-dialog-view /deep/ .el-dialog__body {
  padding: 16px 20px 0 8px !important;
}

.ele-dialog-view /deep/ .el-textarea__inner {
  box-shadow: var(--header-light-shadow);
  border-radius: 0 !important;
  min-height: 285px;
  height: 285px;
}

.ele-dialog-view /deep/ .el-checkbox__label {
  font-size: 12px !important;
}

.ele-border {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  opacity: 0.1;
  border: 1px solid rgba(46, 46, 46, 1);
  background-color: var(--color-primary);
  display: none;
  z-index: 9999;
}
</style>
